//
//  ChoiceEntAddressBookContactViewController.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 6/1/14.
//  Copyright (c) 2014 GuangZhouXuanWu. All rights reserved.
//

#import "ChoiceEntAddressBookContactViewController.h"

#import "ContactCandidateView.h"

#import "ChoiceEntAddressBookContactCell.h"

NSString *const ChoiceEntAddressBookContactViewControllerChoiceContactParamkey = @"ChoiceEntAddressBookContactViewControllerChoiceContactParamkey";

NSString *const ChoiceEntAddressBookContactViewControllerFilterChoiceContactParamkey = @"ChoiceEntAddressBookContactViewControllerFilterChoiceContactParamkey";

NSString *const ChoiceEntAddressBookContactViewControllerIsMutilChoiceContactParamkey = @"ChoiceEntAddressBookContactViewControllerIsMutilChoiceContactParamkey";

NSString *const ChoiceEntAddressBookContactViewControllerCanSelectedContactParamkey = @"ChoiceEntAddressBookContactViewControllerCanSelectedContactParamkey";

NSString *const ChoiceEntAddressBookContactViewControllerVclTypeParamkey = @"ChoiceEntAddressBookContactViewControllerVclTypeParamkey";

@interface ChoiceEntAddressBookContactViewController ()<XUISearchBarDelegate,ContactCandidateViewDelegate>
{
    ContactCandidateView *_candidate;
    
    RSWDataOperation *_manager;
    
    XMSQueueDictionary *_qdData;
    
    XMSQueueDictionary *_searchData;
    
    NSMutableArray *_selectedData;
    
    NSArray *_filterData;
    
    BOOL _mutilChoice;
    
    BOOL _searching;
    
    NSUInteger _vclType;
}

@end

@implementation ChoiceEntAddressBookContactViewController

- (void)viewDidLoad
{
    [self setBackNavigateItemTitle:@"选择人员"];
    
    [super createTableView:XUITabelViewStyleTypePlain|XUITabelViewStyleTypeSearch];
    
    _ctable.height -= 50;
    
    _candidate = [[ContactCandidateView alloc]initWithFrame:CGRectMake(0, _ctable.bottom, self.view.width, 50)];
    _candidate.delegate = self;
    [self.view addSubview:_candidate];
    
    _ctable.searchBar.delegate = self;
    _ctable.searchBar.searchfield.textInputMaxLength = 20;
    _ctable.sectionIndexColor = [UIColor grayColor];
    
    _qdData = [XMSQueueDictionary new];
    
    _searchData = [XMSQueueDictionary new];
    
    if(self.param[ChoiceEntAddressBookContactViewControllerVclTypeParamkey] != nil)
        _vclType = [self.param[ChoiceEntAddressBookContactViewControllerVclTypeParamkey] integerValue];
    
    _selectedData = [NSMutableArray new];
    if(self.param[ChoiceEntAddressBookContactViewControllerChoiceContactParamkey] != nil)
        [_selectedData addObjectsFromArray:self.param[ChoiceEntAddressBookContactViewControllerChoiceContactParamkey]];
    
    if(self.param[ChoiceEntAddressBookContactViewControllerFilterChoiceContactParamkey] != nil)
        _filterData = self.param[ChoiceEntAddressBookContactViewControllerFilterChoiceContactParamkey];
    
    _mutilChoice = YES;
    if(self.param[ChoiceEntAddressBookContactViewControllerIsMutilChoiceContactParamkey] != nil)
    {
        _mutilChoice = [self.param[ChoiceEntAddressBookContactViewControllerIsMutilChoiceContactParamkey] boolValue];
        
        if(_mutilChoice == NO)
        {
            _ctable.height += 50;
            [_candidate removeFromSuperview];
            _candidate = nil;
        }
    }
    
    NSMutableArray *canSelectContact;
    if(self.param[ChoiceEntAddressBookContactViewControllerCanSelectedContactParamkey] != nil)
        canSelectContact = self.param[ChoiceEntAddressBookContactViewControllerCanSelectedContactParamkey];
    
    for(EntAddressBookContact *c in _selectedData)
    {
        UIImage *headImage = nil;
        if(c.logoURL.length >0)
        {
            if([c.logoURL rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
            {
               headImage = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:[XLGContext fileDownloadURL:c.logoURL] forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
            }
            else
            {
                NSString *h = [c.logoURL substringFromIndex:[c.logoURL rangeOfString:ServiceDefaultHeadImageTag].length];
                headImage = [UIImage imageNamed:h];
            }
        }
        [_candidate addContactHeadImageWithHeadImage:headImage andTag:[c.userNumber toNSString]];
    }
    
    [self addMainThreadObserverWithDictionarySelector:[NSDictionary dictionaryWithObject:@"observerHeadImageDownloadQueueHeadImageDownloadResultNotification:" forKey:XLGHeadImageDownloadQueueHeadImageDownloadResultNotification]];
    
    [self addKeyboardObserver];
    
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    if(canSelectContact.count > 0)
    {
        [_manager getEntAddressBookContactDetialWithContactNumber:canSelectContact sort:YES completion:^(NSInteger nResult, NSArray *arList)
        {
             [self requestComplete:nil funcationName:@"loadData" result:nResult output:arList error:nil];
        }];
    }
    else
    {
        [_manager getEntAddressBookWithRefresh:NO completion:^(NSInteger nResult, XMSQueueDictionary *list, NSError *error)
        {
            [self requestComplete:nil funcationName:@"loadData" result:nResult output:list error:nil];
        }];
    }
}

-(XMSQueueDictionary*)data
{
    return _searching == NO ? _qdData : _searchData;
}

-(void)viewControllerDidMoveDealloc
{
    [super viewControllerDidMoveDealloc];
    
    [self removeObserver];
}

#pragma mark --
#pragma mark -- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [ChoiceEntAddressBookContactCell caleHeight];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self data] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ((NSArray*)[[self data] getValueForIndex:section]).count;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [[self data] allKeys];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *l =[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 20)];
    l.backgroundColor = [UIColor clearColor];
    l.text = [_qdData getKeyForIndex:section];
    l.textColor = [UIColor grayColor];
    l.font = [UIFont systemFontOfSize:14];
    
    UIImageView *v = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, tableView.width, 20)];
    v.image = [[UIImage imageNamed:@"tv_sectionbackground.png"] resizeableCenterImage];
    [v addSubview:l];
    
    return v;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChoiceEntAddressBookContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[ChoiceEntAddressBookContactCell alloc]initWithReuseIdentifier:@"cell"];
    }
    
    EntAddressBookContact *c = [((NSArray*)[[self data] getValueForIndex:indexPath.section]) objectAtIndex:indexPath.row];
    
    cell.szTag = [c.userNumber toNSString];
    cell.name.text = c.userName;
    cell.department.text = c.departmentName;
    
    if(_mutilChoice == YES)
    {
        [cell.selector setSelected:NO animated:NO];
        [_selectedData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
        {
            if([[((EntAddressBookContact *)obj).userNumber toNSString] isEqualToString:[c.userNumber toNSString]])
            {
                *stop = YES;
                [cell.selector setSelected:YES animated:NO];
            }
        }];
    }
    else
    {
        cell.hiddenSelector = YES;
    }
    
    if(c.logoURL.length >0)
    {
        if([c.logoURL rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
        {
            XLGHeadImageCache *h = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:[XLGContext fileDownloadURL:c.logoURL] forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
            if(h != nil)
                cell.headImage = h;
            else
                cell.headImage = [UIImage imageNamed:@"img_defaulthead.png"];
        }
        else
        {
            NSString *h = [c.logoURL substringFromIndex:[c.logoURL rangeOfString:ServiceDefaultHeadImageTag].length];
            cell.headImage = [UIImage imageNamed:h];
        }
    }
    else
        cell.headImage = [UIImage imageNamed:@"img_defaulthead.png"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ChoiceEntAddressBookContactCell *cell = (ChoiceEntAddressBookContactCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    [cell.selector setSelected:!cell.selector.selected animated:NO];
    [self choiceEntAddressBookContactCell:cell clickSelector:cell.selector];
}

-(void)choiceEntAddressBookContactCell:(ChoiceEntAddressBookContactCell *)cell clickSelector:(XUISelector *)selector
{
    if(_mutilChoice == YES)
    {
        [[self data] enumerateArrayValueUsingBlock:^(id key, id obj, NSUInteger idx, BOOL *stop)
        {
            EntAddressBookContact *c = obj;
            if([[c.userNumber toNSString] isEqualToString:cell.szTag])
            {
                *stop =YES;
                
                if(selector.selected == YES)
                {
                    [_selectedData addObject:c];
                    
                    UIImage *headImage = nil;
                    
                    if(c.logoURL.length >0)
                    {
                        if([c.logoURL rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
                        {
                            headImage = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:c.logoURL forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
                        }
                        else
                        {
                            NSString *h = [c.logoURL substringFromIndex:[c.logoURL rangeOfString:ServiceDefaultHeadImageTag].length];
                            headImage = [UIImage imageNamed:h];
                        }
                    }
                    
                    [_candidate addContactHeadImageWithHeadImage:headImage andTag:[c.userNumber toNSString]];
                }
                else
                {
                    [_selectedData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                    {
                        if([[((EntAddressBookContact*)obj).userNumber toNSString] isEqualToString:[c.userNumber toNSString]])
                        {
                            *stop = YES;
                            [_selectedData removeObjectAtIndex:idx];
                            
                            [_candidate removeContactHeadImageWithHeadImageTag:[c.userNumber toNSString]];
                        }
                    }];
                }
            }
        }];
    }
    else
    {
        for (ChoiceEntAddressBookContactCell * cell in[_ctable visibleCells])
        {
            cell.selector.selected = NO;
        }
        [_selectedData removeAllObjects];
        [[self data] enumerateArrayValueUsingBlock:^(id key, id obj, NSUInteger idx, BOOL *stop)
        {
            EntAddressBookContact *c = obj;
            if([[c.userNumber toNSString] isEqualToString:cell.szTag])
            {
                *stop =YES;
                
                [_selectedData addObject:c];
            }
        }];
        
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        p.param[ChoiceEntAddressBookContactViewControllerChoiceContactParamkey] = _selectedData;
        p.param[ChoiceEntAddressBookContactViewControllerVclTypeParamkey] = @(_vclType);
        
        [XUINavigationController popWithSwitchParam:p];
    }
}

#pragma mark --
#pragma mark refresh tableView

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    if([szFuncationname isEqualToString:@"loadData"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
        {
            switch(requestResult)
            {
                case YES:
                {
                    _qdData = output;
                    
                    if(_filterData.count>0)
                    {
                        for(XMSNumberInt *userNumber in  _filterData)
                        {
                            [_qdData enumerateKeyValuesUsingBlock:^(id key, id value, NSUInteger idx, BOOL *stop)
                            {
                                __block NSUInteger delIndex = NSNotFound;
                                [(NSMutableArray*)value enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                                {
                                    EntAddressBookContact *c = (EntAddressBookContact*)obj;
                                    if([c.userNumber isEqual:userNumber])
                                    {
                                        delIndex = idx;
                                        *stop = YES;
                                    }
                                }];
                                if(delIndex != NSNotFound)
                                {
                                    *stop = YES;
                                    [(NSMutableArray*)value removeObjectAtIndex:delIndex];
                                    if(((NSMutableArray*)value).count<=0)
                                    {
                                        [_qdData removeObjectAtIndex:idx];
                                    }
                                }
                            }];
                        }
                    }
                    
                    [_ctable reloadData];
                    
                    break;
                }
                default:
                {
                    [UIAlertView showErrorMsg:@"数据请求失败"];
                    break;
                }
            }
        }];
    }
}

#pragma mark --
#pragma mark -- refresh headImage

-(void)observerHeadImageDownloadQueueHeadImageDownloadResultNotification:(NSNotification*)noti
{
    NSString *path =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultPathKey];
    NSString *URL =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultURLKey];
    XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue setCacheWithHeadImageURL:URL andHeadImagePath:path forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
    
    __block XMSNumberInt *n = nil;
    [[self data] enumerateArrayValueUsingBlock:^(id key, id obj, NSUInteger idx, BOOL *stop)
    {
        EntAddressBookContact *c = obj;
        if(c.logoURL.length >0 && [URL rangeOfString:c.logoURL].location != NSNotFound)
        {
            n = c.userNumber;
            *stop =YES;
        }
    }];
    for(ChoiceEntAddressBookContactCell *cell in [_ctable visibleCells])
    {
        if([cell.szTag isEqualToString:[n toNSString]])
        {
            cell.headImage = cache;
            break;
        }
    }
    
    [_candidate refreshContactHeadImageWithHeadImage:cache andTag:[n toNSString]];
}

#pragma mark --
#pragma mark -- search

- (BOOL)clearSearchField:(XUISearchBar *)searchbar
{
    return YES;
}

- (void)searchBar:(XUISearchBar *)searchbar textDidChange:(NSString *)searchText
{
    if(searchText.length>0)
    {
        _searching = YES;
        
        [_searchData removeAllObjects];
        
        [_qdData enumerateArrayValueUsingBlock:^(id key, id obj, NSUInteger idx, BOOL *stop)
        {
            EntAddressBookContact *c = obj;
            if([c.userName rangeOfString:searchText].location != NSNotFound)
            {
                NSMutableArray *ar = [_searchData getValueForKey:key value:^id
                {
                    return [NSMutableArray new];
                }];
                [ar addObject:c];
            }
        }];
        
        [_ctable reloadData];
    }
    else
    {
        _searching = NO;
        [self requestComplete:nil funcationName:@"loadData" result:YES output:_qdData error:nil];
    }
}

- (BOOL)searchBarSearchButtonClicked:(XUISearchBar *)searchbar
{
    [UIViewController closeKeyBoard];
    return YES;
}

#pragma mark --
#pragma mark -- contactCandidateView delegate

-(void)contactCandidata:(ContactCandidateView *)view removeHeadImageWhenClick:(NSString *)szTag
{
    [_qdData enumerateArrayValueUsingBlock:^(id key, id obj, NSUInteger idx, BOOL *stop)
    {
        EntAddressBookContact *c = obj;
        if([[c.userNumber toNSString] isEqualToString:szTag])
        {
            *stop =YES;
            
            XUISelector *selector = nil;
            for(ChoiceEntAddressBookContactCell * cell in [_ctable visibleCells])
            {
                if([cell.szTag isEqualToString:szTag])
                {
                    selector = cell.selector;
                    break;
                }
            }
            
            [selector setSelected:NO animated:NO];
            
            for(EntAddressBookContact *c in _selectedData)
            {
                if([[c.userNumber toNSString] isEqualToString:szTag])
                {
                    [_selectedData removeObject:c];
                    break;
                }
            }
        }
    }];
}

-(void)contactCandidata:(ContactCandidateView *)view acceptWhenClickAcceptBtn:(NSArray *)szTag
{
    XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
    p.param[ChoiceEntAddressBookContactViewControllerChoiceContactParamkey] = _selectedData;
    p.param[ChoiceEntAddressBookContactViewControllerVclTypeParamkey] = @(_vclType);
    
    [XUINavigationController popWithSwitchParam:p];
}

@end
